package com.quotes.ui;

import java.awt.*;
import javax.swing.*;
import org.apache.log4j.*;
import com.quotes.Parameters;
import com.quotes.datamodell.*;
import com.quotes.dates.*;

public class AnalysisPanel extends JPanel implements QuotesListSelectionChangedListener, TimeRangeSelectionChangedListener
{
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(getClass().toString());
	private DataRepository repository = null;
	private Parameters parameters = null;
	private ChartsPanel chartsPanel = null;
	private TimeRange range = TimeRangeFactory.untilToday(TimePeriod.ONE_YEAR);
	private QuotesList selectedQuotes = null;

	public AnalysisPanel(DataRepository repository, Parameters parameters) {
		this.repository = repository;
		this.parameters = parameters;
		
		this.setLayout(new BorderLayout());
		this.buildUserInterface();

		logger.debug("AnalysisPanel created!");
	}
	
	private void buildUserInterface() {
		JPanel mainPanel = new JPanel(new BorderLayout());

		TimeRangeSelectorPanel timeRangeSelectorPanel = new TimeRangeSelectorPanel();
		timeRangeSelectorPanel.addTimeRangeSelectionChangedListener(this);
		mainPanel.add(timeRangeSelectorPanel, BorderLayout.NORTH);
		
		chartsPanel = new ChartsPanel(range, parameters);
		mainPanel.add(chartsPanel, BorderLayout.CENTER);
		
		QuotesListPanel quotesList = new QuotesListPanel(repository);
		quotesList.addQuotesListSelectionChangedEvent(this);
		
		JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, quotesList, mainPanel);
		add(splitPane, BorderLayout.CENTER);
	}

	@Override
	public void selectionChanged(QuotesList list) {
		this.selectedQuotes = list;
		
		if (list.getQuotes().size() == 1) {
			Quotes quotes = list.get(0);
			chartsPanel.setQuotes(quotes);
		}
	}

	@Override
	public void selectionChanged(TimeRange newRange) {
		this.range = newRange;
		
		if (this.selectedQuotes.getQuotes().size() == 1) {
			chartsPanel.setTimeRange(newRange);
		}
	}
}
